package com.searchbyesandhbase.controller;

import com.searchbyesandhbase.entity.doc.ArticleDoc;
import com.searchbyesandhbase.service.ArticleService;
import com.searchbyesandhbase.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * @author LJK
 * @description
 * @date 2024/10/27
 */
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    /**
     * ES-添加文章索引
     * @param articleDoc
     * @return
     */
    @PostMapping("/es/add")
    public Result addArticle(@RequestBody ArticleDoc articleDoc) {
        articleService.addArticleIndex(articleDoc);
        return Result.success();
    }

    /**
     * ES-根据id查询文章
     * @param id
     * @return
     */
    @GetMapping("/es/search/{id}")
    public Result searchArticle(@PathVariable Integer id) {
        return Result.success(articleService.getOneByIndex(id));
    }

    /**
     * HBase Redis-添加文章 添加rowKey至缓存
     * @param articleDocs
     * @return
     */
    @PostMapping("/hbase/add")
    public Result addArticleToHbase(@RequestBody List<ArticleDoc> articleDocs) {
        articleService.addArticleRowKeyAndCache(articleDocs);
        return Result.success();
    }

    /**
     * ES - 根据关键字搜索分页查询文章
     * @param keyword
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/es/search")
    public Result searchArticleByPage(@RequestParam(required = false, defaultValue = "") String keyword,
                                      @RequestParam(required = false, defaultValue = "1") Integer page,
                                      @RequestParam(required = false, defaultValue = "1") Integer size) {
        page=page-1;
        return Result.success(articleService.searchByKeyword(keyword, page, size));
    }

    /**
     * HBase - 根据rowKey查询文章具体信息
     * @param rowKey
     * @return
     * @throws IOException
     */
    @GetMapping("/hbase/search/{rowKey}")
    public Result searchArticleByRowKey(@PathVariable String rowKey) throws IOException {
        return Result.success(articleService.getOneByRowKey(rowKey));
    }
}
